// 线程的封装

#ifndef __THREAD_HPP__
#define __THREAD_HPP__
#include <iostream>
#include <string>
#include <pthread.h>
#include <unistd.h>
#include <functional> //c++11新语法
#include <sys/syscall.h>

// 宏定义，通过系统调用获取线程id
#define get_lwp_id() syscall(SYS_gettid)

using func_t = std::function<void()>; // c++11
const std::string threadnamedefault = "None_name";

class Thread
{
public:
    //构造
    Thread(func_t func, const std::string &name = threadnamedefault)
        : _func(func), _name(name), _isrunning(false)
    {
        std::cout << "creat thread success" << std::endl;
    }

    //线程执行函数
    static void *start_tountin(void *args)
    {
        // 对成员变量的一些设置
        Thread *self = static_cast<Thread *>(args);
        self->_isrunning = true;
        self->_lwpid = get_lwp_id();
        self->_func();
        pthread_exit((void *)0);
    }
    //启动线程
    void Start()
    {
        // 启动封装了线程创建
        int n = pthread_create(&_tid, nullptr, start_tountin, this);
        if (n == 0)
        {
            std::cout << "run thread success" << std::endl;
        }
    }

    //回收线程
    void Join()
    {
        // 回收线程
        if (!_isrunning)
            return; // 还在运行不回收
        int n = pthread_join(_tid, nullptr);
        if (n == 0)
        {
            std::cout << "join thread success" << std::endl;
        }
    }

    //析构
    ~Thread()
    {}
    
private:
    bool _isrunning; // 是否运行
    pthread_t _tid;  // 线程标识符
    pid_t _lwpid;    // 线程id
    std::string _name;
    func_t _func; // 用户要让线程执行的函数
};
#endif